﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO.Compression;
using System.Diagnostics;
using SwParaPlatform2.logger;
using SwParaPlatform2.tools;
using SolidWorks.Interop.sldworks;

namespace SwParaPlatform2
{
    public interface IXmlElementNameValidator
    {
        (bool IsValid, string ViolationReason) ValidateElementName(string name);
    }

    public static class XmlHandler
    {
        private const string ListSeparator = "|~|"; // 使用不常见的分隔符
        private const string ListTag = "IsList"; // 标记列表的属性名称
        private const string AtReplacement = "_rep_at_"; // 用于替换@符号
        private const string PercentReplacement = "_rep_percent_"; // 用于替换%符号
        private const string ArrorReplacement = "_rep_arror_"; // 用于替换>符号
        private const string SpaceReplacement = "_rep_space_"; // 用于替换空格

        private const string LeftKuo_CN_Replacement = "_lkcn_"; // 用于替换（
        private const string RightKuo_CN_Replacement = "_rkcn_"; // 用于替换）
        private const string LeftKuo_EN_Replacement = "_lken_"; // 用于替换(
        private const string RightKuo_EN_Replacement = "_rken_"; // 用于替换)

        private static readonly Dictionary<char, string> ChineseDigits = new Dictionary<char, string>
    {
        { '0', "_零_" }, { '1', "_一_" }, { '2', "_二_" }, { '3', "_三_" },
        { '4', "_四_" }, { '5', "_五_" }, { '6', "_六_" }, { '7', "_七_" },
        { '8', "_八_" }, { '9', "_九_" }
    };

        private static readonly Dictionary<string, char> ChineseToDigit = new Dictionary<string, char>
    {
        { "_零_", '0' }, { "_一_", '1' }, { "_二_", '2' }, { "_三_", '3' },
        { "_四_", '4' }, { "_五_", '5' }, { "_六_", '6' }, { "_七_", '7' },
        { "_八_", '8' }, { "_九_", '9' }
    };


        public static void WriteDictionaryToXml(string filePath, Dictionary<string, Dictionary<string, object>> dictionary, string rootElementName)
        {
            Logger.Instance.Log($"⏩ 进入 WriteDictionaryToXml，filePath=\"{filePath}\", root=\"{rootElementName}\"");
            if (dictionary == null || dictionary.Count == 0)
            {
                Logger.Instance.Log("📭 传入字典为空，保持现有 XML 不变");
                // ① 若目标文件已存在：直接 return，避免删除旧节点。  
                // ② 若文件不存在：既不创建空文件，也不抛异常，直接 return。  
                return;
            }
            try
            {
                XElement root;
                string rootNameEncoded = ReplaceSymbols(rootElementName);
                if (File.Exists(filePath))
                {
                    Logger.Instance.Log($"📄 已存在文件，加载并更新：{filePath}");
                    var document = XDocument.Load(filePath);
                    root = document.Element("Root") ?? new XElement("Root");

                    var existingRootElement = root.Element(rootNameEncoded);
                    if (existingRootElement != null)
                    {
                        Logger.Instance.Log($"🔄 删除旧元素 <{rootNameEncoded}>");
                        existingRootElement.Remove();
                    }

                    var newRootElement = new XElement(rootNameEncoded);
                    AddDictionaryToElement(newRootElement, dictionary.ToDictionary(kvp => kvp.Key, kvp => (object)kvp.Value));
                    root.Add(newRootElement);

                    document.Save(filePath);
                    Logger.Instance.Log("✅ 保存完成（更新模式）");
                }
                else
                {
                    Logger.Instance.Log($"📄 文件不存在，创建新文件：{filePath}");

                    root = new XElement("Root");
                    var rootElement = new XElement(rootNameEncoded);
                    AddDictionaryToElement(rootElement, dictionary.ToDictionary(kvp => kvp.Key, kvp => (object)kvp.Value));
                    root.Add(rootElement);

                    var document = new XDocument(root);
                    document.Save(filePath);
                    Logger.Instance.Log("✅ 保存完成（新建模式）");
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.Log(LogLevel.Error,
                    "❌ WriteDictionaryToXml 发生异常",
                    new LogField("Message", ex.Message),
                    new LogField("Stack", ex.StackTrace ?? ""));
                throw;      // 保持抛出，让调用方决定是否继续处理
            }
        }

        public static Dictionary<string, Dictionary<string, object>> ReadDictionaryFromXml(string rootElementName)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.InitialDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
                openFileDialog.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
                openFileDialog.FilterIndex = 1;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string sourceFilePath = openFileDialog.FileName;
                    string tempFilePath = Path.ChangeExtension(sourceFilePath, ".zip");  // 将后缀改为.zip
                    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(sourceFilePath);  // 获取文件名（不含后缀）
                    string destinationFolderPath = Path.Combine(Path.GetDirectoryName(sourceFilePath), $"_{fileNameWithoutExtension}");  // 解压后的文件夹路径，添加前缀"_"，如"_AAA"

                    // Step 0: 将文件重命名为 .zip 扩展名
                    // File.Move(sourceFilePath, tempFilePath);

                    // Step 1：删掉同名文件夹
                    if (Directory.Exists(destinationFolderPath))
                    {
                        Directory.Delete(destinationFolderPath, true);  // 递归删除文件夹
                    }

                    // Step 2: 解压到目标文件夹
                    ExtractZip(sourceFilePath, destinationFolderPath);

                    // Step 3: 将解压出的文件夹设置为隐藏
                    HideFolder(destinationFolderPath);

                    // Step 4: 获取 DriveConfig.xml 的完整路径
                    string driveConfigPath = FindDriveConfigFile(destinationFolderPath);

                    try
                    {
                        var document = XDocument.Load(driveConfigPath);
                        var root = document.Element("Root");

                        if (root == null)
                        {
                            throw new InvalidOperationException($"Root element 'Root' not found.");
                        }

                        var targetElement = root.Element(ReplaceSymbols(rootElementName));
                        if (targetElement == null)
                        {
                            throw new InvalidOperationException($"Root element '{rootElementName}' not found.");
                        }

                        var dictionary = new Dictionary<string, Dictionary<string, object>>();
                        foreach (var outerElement in targetElement.Elements())
                        {
                            var innerDictionary = ConvertXElementToDictionary(outerElement);
                            dictionary[RestoreSymbols(outerElement.Name.LocalName)] = innerDictionary;
                        }

                        return dictionary;
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Log(LogLevel.Warn, $"Error reading XML file: {ex.Message}");
                    }
                }
            }

            return null;
        }



        public static void ExtractZip(string zipFilePath, string extractPath)
        {
            // 检查是否已经存在解压目标文件夹，如果不存在则创建
            if (!Directory.Exists(extractPath))
            {
                Directory.CreateDirectory(extractPath);
            }

            // 解压 .zip 文件到目标路径
            ZipFile.ExtractToDirectory(zipFilePath, extractPath);

            Logger.Instance.Log($"文件 {zipFilePath} 已解压到 {extractPath}");
        }

        static void CompressFolderToZip(string folderPath, string outputFilePath)
        {
            // 创建 .zip 文件
            ZipFile.CreateFromDirectory(folderPath, outputFilePath, CompressionLevel.Fastest, includeBaseDirectory: false);
            Logger.Instance.Log($"文件夹 {folderPath} 已压缩为 {outputFilePath}");
        }

        // 手动计算相对路径的函数
        static string GetRelativePath(string basePath, string filePath)
        {
            Uri baseUri = new Uri(basePath.EndsWith(Path.DirectorySeparatorChar.ToString()) ? basePath : basePath + Path.DirectorySeparatorChar);
            Uri fileUri = new Uri(filePath);
            return Uri.UnescapeDataString(baseUri.MakeRelativeUri(fileUri).ToString().Replace('/', Path.DirectorySeparatorChar));
        }

        static void HideFolder(string folderPath)
        {
            if (Directory.Exists(folderPath))
            {
                // 设置文件夹属性为“隐藏”
                DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
                directoryInfo.Attributes |= FileAttributes.Hidden;  // 添加隐藏属性
                Logger.Instance.Log($"文件夹已设置为隐藏: {folderPath}");
            }
            else
            {
                Logger.Instance.Log($"文件夹不存在: {folderPath}");
            }
        }

        static string FindDriveConfigFile(string folderPath)
        {
            string driveConfigFilePath = Path.Combine(folderPath, "DriveConfig.xml");

            if (File.Exists(driveConfigFilePath))
            {
                return driveConfigFilePath;  // 返回 DriveConfig.xml 的完整路径
            }
            else
            {
                // 如果没有在根文件夹中找到，可以递归查找子文件夹
                var files = Directory.GetFiles(folderPath, "DriveConfig.xml", SearchOption.AllDirectories);
                if (files.Length > 0)
                {
                    return files[0];  // 返回找到的第一个 DriveConfig.xml 文件
                }
            }

            return null;  // 未找到文件
        }

        // 压缩文件夹为 .yxdcfg 文件
        public static void SaveAndPackConfigFile(string filePath, Dictionary<string, Dictionary<string, object>> dictionary, string rootElementName)
        {
            WriteDictionaryToXml(filePath, dictionary, rootElementName);
            CompressFolderToZip();
        }

        public static void CompressFolderToZip()
        {
            string folderPath = DataStore.Instance.sWorkingPath;  // 要压缩的文件夹路径
            string parentDirectory = Path.GetDirectoryName(folderPath);  // 文件夹的父目录
            string folderName = Path.GetFileName(folderPath);  // 文件夹名称
            string compressedFilePath = Path.Combine(parentDirectory, $"{folderName}.yxdcfg");  // 压缩文件路径，带 _
            string renamedFilePath = Path.Combine(parentDirectory, $"{folderName.TrimStart('_')}.yxdcfg");  // 重命名后的文件路径，不带 _

            // Step 1: 压缩文件夹为 .yxdcfg 文件
            CompressFolderToZip(folderPath, compressedFilePath);
            Logger.Instance.Log($"压缩完成：{compressedFilePath}");

            if (File.Exists(renamedFilePath))
            {
                //DirectoryHelper.ForceDeleteDirectory(renamedFilePath);
                File.Delete(renamedFilePath);
            }
            Logger.Instance.Log($"删除完成：{renamedFilePath}");

            // Step 2: 将 .yxdcfg 文件重命名，去掉开头的 "_"
            File.Move(compressedFilePath, renamedFilePath);

            Logger.Instance.Log($"重命名完成：{renamedFilePath}");
        }

        public static Dictionary<string, object> LoadAllDictionaryFromXml(string sFilePath=null)
        {
            string UIElementName = "UIConfig";
            string RuleElementName = "RuleConfig";
            string PathElementName = "Path";
            string sSelectPath = "SelectPath";
            string DrwElementName = "drwConfig";

            string Note_NameElementName = Defines.Note_NameElementName;
            string Name_NoteElementName = Defines.Name_NoteElementName;

            if (sFilePath == null) 
            {
                using (OpenFileDialog openFileDialog = new OpenFileDialog())
                {
                    openFileDialog.InitialDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
                    openFileDialog.Filter = "参数化平台配置文件 (*.yxdcfg)|*.yxdcfg|所有文件 (*.*)|*.*";
                    openFileDialog.FilterIndex = 1;
                    openFileDialog.RestoreDirectory = true;

                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                    {

                        string sourceFilePath = openFileDialog.FileName;
                        string tempFilePath = Path.ChangeExtension(sourceFilePath, ".zip");  // 将后缀改为.zip
                        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(sourceFilePath);  // 获取文件名（不含后缀）
                        string destinationFolderPath = Path.Combine(Path.GetDirectoryName(sourceFilePath), $"_{fileNameWithoutExtension}");  // 解压后的文件夹路径，添加前缀"_"，如"_AAA"

                        // Step 0: 将文件重命名为 .zip 扩展名
                        // File.Move(sourceFilePath, tempFilePath);

                        // Step 1：删掉同名文件夹
                        if (Directory.Exists(destinationFolderPath))
                        {
                            object[] docs = (object[])SwAppMgr.Instance.iSwApp.GetDocuments();
                            if (docs != null)
                            {
                                Logger.Instance.Log($"当前打开的文档数量：{docs.Length}");
                                foreach (ModelDoc2 doc in docs)
                                {
                                    string name = doc.GetTitle();
                                    SwAppMgr.Instance.iSwApp.CloseDoc(name);
                                    System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
                                }

                                GC.Collect();
                                GC.WaitForPendingFinalizers();
                            }
                            Logger.Instance.Log($"删掉同名文件夹 in LoadAllDictionaryFromXml");
                            DirectoryHelper.ForceDeleteDirectory(destinationFolderPath);
                            //Directory.Delete(destinationFolderPath, true);  // 递归删除文件夹
                        }

                        // Step 2: 解压到目标文件夹
                        ExtractZip(sourceFilePath, destinationFolderPath);
                        DataStore.Instance.sWorkingPath = destinationFolderPath;

                        // Step 3: 将解压出的文件夹设置为隐藏
                        HideFolder(destinationFolderPath);

                        // Step 4: 获取 DriveConfig.xml 的完整路径
                        string driveConfigPath = FindDriveConfigFile(destinationFolderPath);
                        var dlgUIConfig = LoadOneDictionaryFromXml(driveConfigPath, UIElementName);
                        var dlgRuleConfig = LoadOneDictionaryFromXml(driveConfigPath, RuleElementName);
                        var PathConfig = LoadOneDictionaryFromXml(driveConfigPath, PathElementName);

                        var dNote_NameData_Pack = LoadOneDictionaryFromXml(driveConfigPath, Note_NameElementName);
                        var dName_NoteData_Pack = LoadOneDictionaryFromXml(driveConfigPath, Name_NoteElementName);
                        var dDrwDict = LoadOneDictionaryFromXml(driveConfigPath, DrwElementName);

                        var dNote_NameElementName =
                        dNote_NameData_Pack.TryGetValue(Note_NameElementName, out var tempDict)
                        ? tempDict
                        : new Dictionary<string, object>();

                        var dName_NoteElementName =
                        dName_NoteData_Pack.TryGetValue(Name_NoteElementName, out var tempDict2)
                        ? tempDict2
                        : new Dictionary<string, object>();


                        var dictionary = new Dictionary<string, object>
                    {
                        {UIElementName,  dlgUIConfig},
                        {RuleElementName,  dlgRuleConfig},
                        {PathElementName,  PathConfig},
                        {Note_NameElementName,  dNote_NameElementName},
                        {Name_NoteElementName,  dName_NoteElementName},
                        {sSelectPath,  sourceFilePath},
                        {DrwElementName,  dDrwDict},
                    };

                        return dictionary;
                        
                    }

                    Logger.Instance.Log(LogLevel.Warn, "请选择正确的配置xml文件");
                    return null;
                }
            }
            else
            {
                string filePath = sFilePath;

                var dlgUIConfig = LoadOneDictionaryFromXml(filePath, UIElementName);
                var dlgRuleConfig = LoadOneDictionaryFromXml(filePath, RuleElementName);
                var PathConfig = LoadOneDictionaryFromXml(filePath, PathElementName);

                var dictionary = new Dictionary<string, object>
                    {
                        {UIElementName,  dlgUIConfig},
                        {RuleElementName,  dlgRuleConfig},
                        {PathElementName,  PathConfig},
                    };

                return dictionary;
            }
            
        }

        public static Dictionary<string, Dictionary<string, object>> LoadOneDictionaryFromXml(string filePath, string rootElementName)
        {
            try
            {
                var document = XDocument.Load(filePath);
                var root = document.Element("Root");

                if (root == null)
                {
                    throw new InvalidOperationException($"Root element 'Root' not found.");
                }

                var targetElement = root.Element(ReplaceSymbols(rootElementName));
                if (targetElement == null)
                {
                    throw new InvalidOperationException($"Root element '{rootElementName}' not found.");
                }

                var dictionary = new Dictionary<string, Dictionary<string, object>>();
                foreach (var outerElement in targetElement.Elements())
                {
                    var innerDictionary = ConvertXElementToDictionary(outerElement);
                    dictionary[RestoreSymbols(outerElement.Name.LocalName)] = innerDictionary;
                }

                return dictionary;
            }
            catch (Exception ex)
            {
                Logger.Instance.Log(LogLevel.Warn, $"配置文件未完成设置或损坏，请重新新建配置或联系技术人员处理: {ex.Message}");
                return new Dictionary<string, Dictionary<string, object>>();
            }
        }

        private static void AddDictionaryToElement(XElement element, object dictionary)
        {
            if (dictionary is Dictionary<string, object> dict)
            {
                foreach (var kvp in dict)
                {
                    ProcessKeyValuePair(element, kvp);
                }
            }
            else if (dictionary is Dictionary<string, Dictionary<string, object>> nestedDict)
            {
                foreach (var kvp in nestedDict)
                {
                    ProcessKeyValuePair(element, kvp);
                }
            }
            else if (dictionary is KeyValuePair<string, object> kvp)
            {
                ProcessKeyValuePair(element, kvp);
            }
            else if (dictionary is KeyValuePair<string, KeyValuePair<string, object>> kvpNested)
            {
                var nestedElement = new XElement(ReplaceSymbols(kvpNested.Key));
                AddDictionaryToElement(nestedElement, kvpNested.Value);
                element.Add(nestedElement);
            }
            else if (dictionary is KeyValuePair<string, Dictionary<string, object>> kvpDict)
            {
                var nestedElement = new XElement(ReplaceSymbols(kvpDict.Key));
                AddDictionaryToElement(nestedElement, kvpDict.Value);
                element.Add(nestedElement);
            }
            else if (dictionary is IEnumerable<object> list)
            {
                foreach (var item in list)
                {
                    if (item is Dictionary<string, object> listDict)
                    {
                        AddDictionaryToElement(element, listDict);
                    }
                    else if (item is Dictionary<string, Dictionary<string, object>> nestedDictInList)
                    {
                        AddDictionaryToElement(element, nestedDictInList);
                    }
                    else if (item is KeyValuePair<string, object> kvpItem)
                    {
                        ProcessKeyValuePair(element, kvpItem);
                    }
                    else if (item is KeyValuePair<string, KeyValuePair<string, object>> kvpNestedItem)
                    {
                        var nestedElement = new XElement(ReplaceSymbols(kvpNestedItem.Key));
                        AddDictionaryToElement(nestedElement, kvpNestedItem.Value);
                        element.Add(nestedElement);
                    }
                    else if (item is KeyValuePair<string, Dictionary<string, object>> kvpDictItem)
                    {
                        var nestedElement = new XElement(ReplaceSymbols(kvpDictItem.Key));
                        AddDictionaryToElement(nestedElement, kvpDictItem.Value);
                        element.Add(nestedElement);
                    }
                    else if (item is IEnumerable<object> nestedList)
                    {
                        AddDictionaryToElement(element, nestedList);
                    }
                    else
                    {
                        element.Add(new XElement("Item", item?.ToString() ?? string.Empty));
                    }
                }
            }
        }

        private static Dictionary<string, object> ConvertXElementToDictionary(XElement element)
        {
            var dictionary = new Dictionary<string, object>();

            foreach (var innerElement in element.Elements())
            {
                if (innerElement.HasElements)
                {
                    if (innerElement.Attribute(ListTag) != null) // 检查是否是列表
                    {
                        var list = innerElement.Elements()
                                               .Select(ConvertXElementToDictionary)
                                               .ToList<object>();
                        dictionary[RestoreSymbols(innerElement.Name.LocalName)] = list;
                    }
                    else
                    {
                        dictionary[RestoreSymbols(innerElement.Name.LocalName)] = ConvertXElementToDictionary(innerElement);
                    }
                }
                else
                {
                    if (innerElement.Attribute(ListTag) != null) // 检查是否是简单的列表
                    {
                        if (innerElement.Value.Contains(ListSeparator))
                        {
                            // 处理 List<string> 格式
                            var list = innerElement.Value.Split(new[] { ListSeparator }, StringSplitOptions.None).ToList();
                            dictionary[RestoreSymbols(innerElement.Name.LocalName)] = list;
                        }
                        else
                        {
                            // 处理 List<object> 格式
                            var list = innerElement.Value.Split(new[] { ListSeparator }, StringSplitOptions.None).ToList<object>();
                            dictionary[RestoreSymbols(innerElement.Name.LocalName)] = list;
                        }
                    }
                    else
                    {
                        dictionary[RestoreSymbols(innerElement.Name.LocalName)] = innerElement.Value;
                    }
                }
            }

            return dictionary;
        }

        public static string ReplaceFirstLeadingDigitWithChinese(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
                return name;

            // 只处理开头第一个字符
            if (char.IsDigit(name[0]))
            {
                if (ChineseDigits.TryGetValue(name[0], out string chinese))
                {
                    return chinese + name.Substring(1);
                }
            }

            return name; // 不以数字开头或不是有效数字，原样返回
        }

        public static string ReplaceFirstLeadingChineseWithDigit(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
                return name;

            foreach (var pair in ChineseToDigit)
            {
                if (name.StartsWith(pair.Key))
                {
                    // 将第一个匹配项替换为阿拉伯数字
                    return pair.Value + name.Substring(pair.Key.Length);
                }
            }

            return name; // 没有匹配，返回原始字符串
        }

        private static string ReplaceSymbols(string name)
        {
            name = ReplaceFirstLeadingDigitWithChinese(name);
            return name.Replace("@", AtReplacement)
                .Replace("%", PercentReplacement)
                .Replace(">", ArrorReplacement)
                .Replace("（", LeftKuo_CN_Replacement)
                .Replace("）", RightKuo_CN_Replacement)
                .Replace("(", LeftKuo_EN_Replacement)
                .Replace(")", RightKuo_EN_Replacement)
                .Replace(" ", SpaceReplacement);
        }

        private static string RestoreSymbols(string name)
        {
            name = ReplaceFirstLeadingChineseWithDigit(name);
            return name.Replace(AtReplacement, "@")
                .Replace(PercentReplacement, "%")
                .Replace(ArrorReplacement, ">")
                .Replace(LeftKuo_CN_Replacement, "（")
                .Replace(RightKuo_CN_Replacement, "）")
                .Replace(LeftKuo_EN_Replacement, "(")
                .Replace(RightKuo_EN_Replacement, ")")
                .Replace(SpaceReplacement, " ");
        }

        private static void ProcessKeyValuePair(XElement element, KeyValuePair<string, object> kvp)
        {
            if (kvp.Value is Dictionary<string, object> dict)
            {
                Logger.Instance.Log($"ProcessKeyValuePair = {kvp.Key}, replace = {ReplaceSymbols(kvp.Key)}");
                var nestedElement = new XElement(ReplaceSymbols(kvp.Key));
                AddDictionaryToElement(nestedElement, dict);
                element.Add(nestedElement);
            }
            else if (kvp.Value is Dictionary<string, Dictionary<string, object>> nestedDict)
            {
                var nestedElement = new XElement(ReplaceSymbols(kvp.Key));
                AddDictionaryToElement(nestedElement, nestedDict);
                element.Add(nestedElement);
            }
            else if (kvp.Value is KeyValuePair<string, object> innerKvp)
            {
                var nestedElement = new XElement(ReplaceSymbols(kvp.Key));
                ProcessKeyValuePair(nestedElement, innerKvp);
                element.Add(nestedElement);
            }
            else if (kvp.Value is KeyValuePair<string, Dictionary<string, object>> dictKvp)
            {
                var nestedElement = new XElement(ReplaceSymbols(kvp.Key));
                ProcessKeyValuePair(nestedElement, new KeyValuePair<string, object>(dictKvp.Key, dictKvp.Value));
                element.Add(nestedElement);
            }
            else if (kvp.Value is List<string> simpleList)
            {
                // 针对简单字符串列表处理
                var innerElement = new XElement(ReplaceSymbols(kvp.Key), string.Join(ListSeparator, simpleList));
                innerElement.SetAttributeValue(ListTag, true);
                element.Add(innerElement);
            }
            else if (kvp.Value is IEnumerable<object> list)
            {
                var listElement = new XElement(ReplaceSymbols(kvp.Key));
                listElement.SetAttributeValue(ListTag, true); // 标记为列表

                foreach (var item in list)
                {
                    ProcessKeyValuePair(listElement, new KeyValuePair<string, object>("Item", item));
                }
                element.Add(listElement);
            }
            else
            {
                var innerElement = new XElement(ReplaceSymbols(kvp.Key?.ToString() ?? string.Empty), kvp.Value?.ToString() ?? string.Empty);
                element.Add(innerElement);
            }
        }


        private static void ProcessKeyValuePair(XElement element, KeyValuePair<string, Dictionary<string, object>> kvp)
        {
            var nestedElement = new XElement(ReplaceSymbols(kvp.Key));
            AddDictionaryToElement(nestedElement, kvp.Value);
            element.Add(nestedElement);
        }

        public static string GetFilePath()
        {
            string filePath = Path.Combine(DataStore.Instance.sWorkingPath, "DriveConfig.xml");
            return filePath;
        }

        public static (bool IsValid, string ViolationReason) ValidateElementName(string name, string sCheckType)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                return (false, $"{sCheckType}:{name}。名称不能为空或仅包含空白字符。");
            }

            if (!IsValidStartCharacter(name[0]))
            {
                return (false, $"{sCheckType}:{name}。名称必须以中文、字母、下划线、或其他合法字符开头。");
            }

            // Check for invalid characters
            if (!Regex.IsMatch(name, @"^[\w-]+$"))
            {
                return (false, $"{sCheckType}:{name}。名称包含无效字符。");
            }

            // Check if it is an XML reserved word (e.g., 'xml')
            var reservedWords = new[] { "xml", "XML", "Xml" };
            if (Array.Exists(reservedWords, word => string.Equals(name, word, StringComparison.OrdinalIgnoreCase)))
            {
                return (false, $"{sCheckType}:{name}。名称不能是 XML 保留字。");
            }

            return (true, string.Empty); // Valid element name
        }

        private static bool IsValidStartCharacter(char c)
        {
            // 检查是否为字母、下划线或其他合法 Unicode 字符
            return char.IsLetter(c) || c == '_' || char.GetUnicodeCategory(c) == System.Globalization.UnicodeCategory.OtherLetter;
        }
    }
}
